package cn.yili12.business.repository;

import cn.yili12.business.entity.CountBean;
import cn.yili12.business.entity.MessageDb;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public interface MessageRepository extends JpaRepository<MessageDb, Long> {

    @Modifying
    @Query("update MessageDb set readTime = ?1,status = ?2 where no = ?3")
    int updateRead(Date date, Integer status, String no);


    @Modifying
    @Query("update MessageDb set readTime = ?1,status = ?2 where no in ?3")
    int updateBatchRead(Date date, Integer status, List<String> nos);

    @Query(value = "from MessageDb where (fromUser = ?1 and toUser = ?2) or (toUser = ?1 and fromUser = ?2 ) order by sendTime desc",
            countQuery = "select count(id) from MessageDb where (fromUser = ?1 and toUser = ?2) or (toUser = ?1 and fromUser = ?2 )")
    Page<MessageDb> findHistory(String userId, String friendId, Pageable pageable);


    //    @Query(value = "select a from MessageDb a inner join (select max(sendTime) time FROM MessageDb where toUser = ?1 GROUP BY fromUser) b on a.sendTime=b.time")
    @Query(value = "SELECT a.* FROM chat_message a INNER JOIN ( SELECT max(send_time) time FROM chat_message where to_user=?1 GROUP BY from_user) b ON a.send_time=b.time", nativeQuery = true)
    List<MessageDb> findLastMessage(String userId);


    @Query("select new cn.yili12.business.entity.CountBean(fromUser,count(id)) from MessageDb where toUser = ?1 and status=0 GROUP BY fromUser")
    List<CountBean> findUnRead(String userId);
}
